package io.file;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

class FileRead {

	public static void main(String[] args) throws IOException {
		BufferedReader buf = new BufferedReader(
				new InputStreamReader(System.in));
		String str = "", fileName;
		char chr;
		try {
			do {
				System.out.print("Stream Type (Byte/Char): ");
				chr = buf.readLine().charAt(0);
				switch (chr) {
				case 'c':
				case 'C':
					break;
				case 'b':
				case 'B':
					break;
				default:
					chr = 'r';
				}
			} while (chr == 'r');
			do {
				System.out.print("File Opertions (Read/Write/Exit): ");
				str = buf.readLine() + chr;
				switch (MenuOption.toEnum(str)) {
				case READB:
					System.out.print("FileName: ");
					fileName = buf.readLine();
					FileInputStream fin = new FileInputStream(fileName);
					int i;
					/*
					 * Optimized loop to print file contents:
					 * 
					 * while ((i =fin.read()) != -1) System.out.print((char) i);
					 */
					do {
						i = fin.read();
						if (i != -1) System.out.print((char) i);
					} while (i != -1);
					fin.close();
					break;
				case READC:
					System.out.print("FileName: ");
					fileName = buf.readLine();
					FileReader fr = new FileReader(fileName);
					BufferedReader br = new BufferedReader(fr);
					String s;
					while ((s = br.readLine()) != null)
						System.out.println(s);
					break;
				case WRITEB:
					System.out.println("Implementation missing");
					break;
				case WRITEC:
					System.out.println("Implementation missing");
					break;
				case EXIT:
					System.out.println("Successful exit");
					break;
				default:
					str = "repeat";
				}
			} while (str.equals("repeat"));

		} catch (FileNotFoundException e) {
			System.out.println("File Not Found.");
			return;
		} catch (IOException e) {
			System.out.println("Unknown error occured.");
			e.printStackTrace();
		}
	}
}
